package com.yanqu.road.server.gameplayer.module.minibind;

import com.alibaba.fastjson.JSONObject;
import com.yanqu.road.entity.player.UserWechatBind;
import com.yanqu.road.logic.config.ChannelConfig;
import com.yanqu.road.pb.common.ConfigProto;
import com.yanqu.road.server.GameServer;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.manger.config.WechatBindMgr;
import com.yanqu.road.server.protocol.ClientProtocol;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.server.protocol.GameProtocol;
import com.yanqu.road.utils.MD5Security;
import com.yanqu.road.utils.date.DateHelper;
import com.yanqu.road.utils.executor.GeneralTask;
import com.yanqu.road.utils.http.HttpHelper;
import com.yanqu.road.utils.string.StringUtils;

import java.net.URLDecoder;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

public class WechatBindQueryTask extends GeneralTask {
    private int protocol;
    private GamePlayer player;

    public WechatBindQueryTask(int protocol, GamePlayer player) {
        this.protocol = protocol;
        this.player = player;
    }

    @Override
    public void doRun() {
        try {
            if (protocol == GameProtocol.S_WECHAT_BIND_ROLE_CANCEL_BIND) {
                Map<String, String> paramMap = new TreeMap<>();
                paramMap.put("uid", player.getUserInfo().getPlatformUserId());
                paramMap.put("game_id", player.getModule(WechatBindModule.class).getGameId());
                paramMap.put("server_id", String.valueOf(GameServer.getInstance().getServerId()));
                paramMap.put("role_id", String.valueOf(player.getUserId()));
                paramMap.put("time", String.valueOf(DateHelper.getCurrentSecond()));

                StringBuilder signBuilder = new StringBuilder();
                signBuilder.append(paramMap.get("uid")).append(paramMap.get("game_id")).append(paramMap.get("server_id")).append(paramMap.get("role_id")).append(paramMap.get("time")).append(ChannelConfig.WX_BIND_INTERFACE_SECRET);
                String sign = MD5Security.md5(signBuilder.toString()).toLowerCase();
                paramMap.put("sign", sign);

                String result = HttpHelper.doGet(ChannelConfig.WX_CANCEL_BIND_URL, paramMap, "UTF-8");

                JSONObject resultObject = JSONObject.parseObject(result);
                int code = resultObject.getIntValue("code");
                String msg = URLDecoder.decode(resultObject.getString("msg"), "UTF-8");
                if (code != 1) {
                    WechatBindMgr.getLogger().info("取消微信绑定角色失败，userId:{},code:{},msg:{}", player.getUserId(), code, msg);
                }

                ConfigProto.WechatBindRoleCancelBindRespMsg.Builder respMsg = ConfigProto.WechatBindRoleCancelBindRespMsg.newBuilder();
                respMsg.setRet(0);
                respMsg.setCode(code);
                player.sendPacket(ClientProtocol.U_WECHAT_BIND_ROLE_CANCEL_BIND, respMsg);

            } else if (protocol == GameProtocol.S_WECHAT_BIND_ROLE_INFO){
                UserWechatBind userData = player.getModule(WechatBindModule.class).getUserData();
                int code = 0;
                int ret = 0;

                SortedMap<String, String> paramMap = new TreeMap<>();
                paramMap.put("uid", player.getUserInfo().getPlatformUserId());
                paramMap.put("game_id", player.getModule(WechatBindModule.class).getGameId());
                paramMap.put("server_id", String.valueOf(GameServer.getInstance().getServerId()));
                paramMap.put("role_id", String.valueOf(player.getUserId()));
                paramMap.put("time", String.valueOf(DateHelper.getCurrentSecond()));
                StringBuilder signBuilder = new StringBuilder();
                signBuilder.append(paramMap.get("uid")).append(paramMap.get("game_id")).append(paramMap.get("server_id")).append(paramMap.get("role_id")).append(paramMap.get("time")).append(ChannelConfig.WX_BIND_INTERFACE_SECRET);
                String sign = MD5Security.md5(signBuilder.toString()).toLowerCase();
                paramMap.put("sign", sign);
                String result = HttpHelper.doGet(ChannelConfig.WX_CHECK_BIND_STATUS_URL, paramMap, "UTF-8");
                if (StringUtils.isNullOrEmpty(result)) {
                    ret = GameErrorCode.E_ERROR_DATA;
                }else{
                    JSONObject resultObject = JSONObject.parseObject(result);
                    code = resultObject.getIntValue("code");
                    String msg = URLDecoder.decode(resultObject.getString("msg"), "UTF-8");

                    if (code == 2) {
                        userData.setBind(true);
                    } else if (code != 1) {
                        WechatBindMgr.getLogger().info("查询微信绑定角色信息失败，userId:{},code:{},msg:{}", player.getUserId(), code, msg);
                    } else if (code == 1) {
                        userData.setBind(false);
                    }
                }

                ConfigProto.WechatBindRoleInfoRespMsg.Builder respMsg = ConfigProto.WechatBindRoleInfoRespMsg.newBuilder();
                respMsg.setRet(ret);
                respMsg.setCode(code);
                respMsg.setExpository(ChannelConfig.WX_BIND_EXPOSITORY);

                player.sendPacket(ClientProtocol.U_WECHAT_BIND_ROLE_INFO, respMsg);
            }

        } catch (Exception e) {
            WechatBindMgr.getLogger().error("WechatBindQueryTask err，userId:{},protocol:{},error:{}", player.getUserId(), protocol, e);
        }
    }
}
